/*
* Copyright 2011 Andy Lee.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package uk.co.optimisticpanda.remoteweb.command

import java.util.List;

class CommandSet {
	List commands;
	List variables;
	
	
	void setCommands(List cs){
		this.commands = cs
		CommandUtils.traverse (cs){
			if (it.executable){
				it.executable.variableFinder = this;
			}
		}
	}

	def getValue(String name){
		Variable v = variables.find { it.name == name }
	    if(!v){
			throw new RuntimeException("no variable with name of " + name)
		}
		v.value
	}
		
	def run(def driver){
		variables.each {
			println "Define value for variable named [" + it.name + "] (Enter for default):"
			def userValue = new Scanner(System.in).nextLine()
			it.value  = userValue ? userValue : it.value
			println()
		}
		
		CommandUtils.traverse(commands, {println it.container ? it.description : "\t"+it.description; it.execute(driver)})
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((commands == null) ? 0 : commands.hashCode());
		result = prime * result
				+ ((variables == null) ? 0 : variables.hashCode());
		return result;
	}


	@Override
	public boolean equals(Object obj) {
		if (this.is(obj))
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		CommandSet other = (CommandSet) obj;
		if (commands == null) {
			if (other.commands != null)
				return false;
		} else if (!commands.equals(other.commands))
			return false;
		if (variables == null) {
			if (other.variables != null)
				return false;
		} else if (!variables.equals(other.variables))
			return false;
		return true;
	}
}
